package com.yjy.fuyao.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjy.fuyao.ucenter.client.StatisticsClient;
import com.yjy.fuyao.ucenter.entity.User;
import com.yjy.fuyao.ucenter.entity.query.UserQuery;
import com.yjy.fuyao.ucenter.entity.vo.LoginVo;
import com.yjy.fuyao.ucenter.entity.vo.RegisterVo;
import com.yjy.fuyao.ucenter.entity.vo.UserQueryVo;
import com.yjy.fuyao.ucenter.mapper.UserMapper;
import com.yjy.fuyao.ucenter.mapper.UserMapper;
import com.yjy.fuyao.ucenter.service.UserService;
import com.yjy.fuyao.ucenter.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjy.fuyao.utils.exception.BusinessException;
import com.yjy.fuyao.utils.util.JwtUtils;
import com.yjy.fuyao.utils.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author yjy
 * @since 2021-08-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private StatisticsClient statisticsClient;

    /**
     * 会员登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {

        String mail = loginVo.getMail();
        String password = loginVo.getPassword();

        //校验参数
        if(StringUtils.isEmpty(mail) ||
                StringUtils.isEmpty(password)) {
            throw new BusinessException("error",20001);
        }

        //获取会员
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("mail", mail));
        if(null == user) {
            throw new BusinessException("error",20001);
        }

        //校验密码
        if(!MD5.encrypt(password).equals(user.getPassword())) {
            throw new BusinessException("error",20001);
        }

        //校验是否被禁用
        if(user.getIsDisabled()) {
            throw new BusinessException("error",20001);
        }

        statisticsClient.addLoginNum();

        //使用JWT生成token字符串
        String token = JwtUtils.getJwtToken(user.getId(), user.getNickname());

        return token;
    }

    /**
     * 会员注册
     * @param registerVo
     */
    @Override
    public void register(RegisterVo registerVo) {
        //获取注册信息，进行校验
        String nickname = registerVo.getNickname();
        String mail = registerVo.getMail();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        //校验参数
        if(StringUtils.isEmpty(nickname) ||
                StringUtils.isEmpty(mail) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(code)) {
            throw new BusinessException("error",20001);
        }

        //校验校验验证码
        //从redis获取发送的验证码
        String mailCode = (String) redisTemplate.opsForValue().get("fuyao:mail:code:" + mail);
        System.out.println("mailCode:"+mailCode);
        System.out.println("mail:"+mail);
        if(!code.equals(mailCode)) {
            throw new BusinessException("error",20001);
        }

        //查询数据库中是否存在相同的邮箱
        Integer count = baseMapper.selectCount(new QueryWrapper<User>().eq("mail", mail));
        if(count.intValue() > 0) {
            throw new BusinessException("error",20001);
        }

        //添加注册信息到数据库
        User user = new User();
        user.setNickname(nickname);
        user.setMail(mail);
        user.setPassword(MD5.encrypt(password));
        user.setIsDisabled(false);
        user.setAvatar("https://fy-file2022.oss-cn-shenzhen.aliyuncs.com/avatar/default.jpg");
        this.save(user);
    }

    @Override
    public User getLoginInfo(String userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public User getByOpenid(String openid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Integer countRegisterByDay(String day) {
        return baseMapper.selectRegisterCount(day);
    }

    @Override
    public IPage<User> listPage(Page<User> pageParam, UserQuery userQuery) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userQuery.getId() != null,User::getId,userQuery.getId())
                .eq(userQuery.getMail() != null,User::getMail,userQuery.getMail())
                .eq(userQuery.getIsDisabled() != null,User::getIsDisabled,userQuery.getIsDisabled())
                .eq(userQuery.getNickname() != null,User::getNickname,userQuery.getNickname())
                .eq(userQuery.getSex() != null,User::getSex,userQuery.getSex())
                .ge(userQuery.getBeginTime() != null,User::getGmtCreate,userQuery.getBeginTime())
                .le(userQuery.getEndTime() != null,User::getGmtCreate,userQuery.getEndTime());

        return baseMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public boolean changeIsDisabled(String id, Integer isDisabled) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(User::getId,id)
                .set(User::getIsDisabled,isDisabled);
        boolean update = userService.update(updateWrapper);
        return update;
    }
}
